package com.chu.interceptor;

import com.chu.entity.Employee;
import com.chu.entity.Menu;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.ResourceBundle;

public class PowerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前期条件，认证通过以后

        //判断是否是公开地址/匿名地址
        ResourceBundle resourceBundle = ResourceBundle.getBundle("openAddress");
        String requestURI = request.getRequestURI();
        if(resourceBundle.containsKey(requestURI)){
            return true;
        }
        //判断是否是公共地址
        ResourceBundle resourceBundle2 = ResourceBundle.getBundle("publicAddress");
        if(resourceBundle2.containsKey(requestURI)){
            return true;
        }
        //判断请求地址是否属于当前用户权限
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        List<Menu> oneList = employee.getRole().getMenuList();
        for (Menu oneMenu : oneList) {
            if(requestURI.equals(oneMenu.getUrl())){
                return true;
            }
            List<Menu> twoList = oneMenu.getMenuList();
            for (Menu twoMenu : twoList) {
                if(requestURI.equals(twoMenu.getUrl())){
                    return true;
                }
            }
        }
        //判断是否是permission的请求地址
        List<Menu> permissionList = employee.getRole().getPermissionList();
        for (Menu menu : permissionList) {
            if(requestURI.equals(menu.getUrl())){
                return true;
            }
        }
        //跳转页面
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<script>location.href='/error.jsp'</script>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
